<template>
  <div 
    class="manager-window"
    :style="{ 
      transform: `translate(${position.x}px, ${position.y}px)`,
      height: isMinimized ? '40px' : '500px',
      width: isMinimized ? '150px' : '400px'
    }"
  >
    <div class="window-container">
      <div class="header" @mousedown="startDrag">
        <span>文件传输管理</span>
        <div class="window-controls">
          <el-button link @click="toggleMinimize">
            <el-icon><Minus /></el-icon>
          </el-button>
          <el-button link @click="close">
            <el-icon><Close /></el-icon>
          </el-button>
        </div>
      </div>
      
      <div class="manager-content" v-show="!isMinimized">
        <el-tabs type="border-card" stretch>
          <el-tab-pane label="上传">
            <div class="upload-list">
              <!-- 活动中的任务 -->
              <div v-if="activeUploads.length > 0" class="section-title">
                <el-icon><Clock /></el-icon> 进行中的上传
              </div>
              <UploadManager 
                v-for="file in activeUploads" 
                :key="file.id"
                :uploadFile="file"
                @pause="pauseUpload(file)"
                @resume="resumeUpload(file)"
                @retry="retryUpload(file)"
                @remove="removeUpload(file.id)"
              />
              
              <!-- 已完成的任务 -->
              <div v-if="completedUploads.length > 0" class="section-title">
                <el-icon><CircleCheck /></el-icon> 已完成的上传
              </div>
              <UploadManager 
                v-for="file in completedUploads" 
                :key="'completed-'+file.id"
                :uploadFile="file"
                @retry="retryUpload(file)"
                @remove="removeUpload(file.id)"
              />
              
              <!-- 失败的任务 -->
              <div v-if="failedUploads.length > 0" class="section-title">
                <el-icon><CircleClose /></el-icon> 失败的上传
              </div>
              <UploadManager 
                v-for="file in failedUploads" 
                :key="'failed-'+file.id"
                :uploadFile="file"
                @retry="retryUpload(file)"
                @remove="removeUpload(file.id)"
              />
            </div>
            <div v-if="!allUploads.length" class="empty-state">
              <el-icon><Document /></el-icon>
              <p>没有上传任务</p>
            </div>
          </el-tab-pane>
          
          <el-tab-pane label="下载">
            <div class="download-list">
              <DownloadManager 
                v-for="file in downloadFiles" 
                :key="file.id"
                :downloadFile="file"
                @pause="pauseDownload(file.id)"
                @resume="resumeDownload(file.id)"
              />
            </div>
            <div v-if="!downloadFiles.length" class="empty-state">
              <el-icon><Download /></el-icon>
              <p>没有进行中的下载任务</p>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount, computed } from 'vue';
import { Minus, Close, Document, Download } from '@element-plus/icons-vue';
import UploadManager from './UploadManager.vue';
import DownloadManager from './DownloadManager.vue';
import { ElMessage } from 'element-plus';
import eventBus from '@/utils/eventBus';
import { useDownloadStore } from '@/stores/downloadStore';
import { useUploadStore } from '@/stores/uploadStore'; // 导入 uploadStore

const downloadStore = useDownloadStore();
const uploadStore = useUploadStore(); // 使用 uploadStore

const downloadFiles = computed(() => downloadStore.downloads);
const uploadFiles = computed(() => uploadStore.activeUploads); // 从 store 获取上传任务

const allUploads = computed(() => uploadStore.allUploads);
const activeUploads = computed(() => uploadStore.activeUploads);
const completedUploads = computed(() => uploadStore.completedUploads);
const failedUploads = computed(() => uploadStore.failedUploads);
const isMinimized = ref(false)
const isDragging = ref(false)
const dragStart = reactive({ x: 0, y: 0 })
// 从 localStorage 恢复位置
const position = reactive({ 
  x: parseInt(localStorage.getItem('managerPosX')) || window.innerWidth - 420,
  y: parseInt(localStorage.getItem('managerPosY')) || window.innerHeight - 520
});

// 按状态排序：上传中 > 暂停 > 完成
const sortedUploadFiles = computed(() => {
  return [...uploadFiles.value].sort((a, b) => {
    const statusOrder = { 
      uploading: 1, 
      paused: 2, 
      completed: 3 
    };
    return statusOrder[a.status] - statusOrder[b.status];
  });
});

onMounted(() => {
  position.x = window.innerWidth - 420;
  position.y = window.innerHeight - 520;
  
  // 监听新的上传任务
  eventBus.on('new-upload-task', handleNewUploadTask);
  // 监听下载事件
  eventBus.on('download-file', handleDownload);
})

onBeforeUnmount(() => {
  eventBus.off('new-upload-task', handleNewUploadTask);
  eventBus.off('download-file', handleDownload);
})

// 处理新的上传任务
function handleNewUploadTask(uploadTask) {
  // 任务已通过 store 添加，这里不需要额外操作
}

// 处理下载事件
function handleDownload(fileInfo) {
  const existingFile = downloadStore.downloads.find(f => f.id === fileInfo.id);
  if (existingFile) {
    ElMessage.info('该文件已在下载队列中');
    return;
  }
  
  downloadStore.addDownload({
    ...fileInfo,
    downloadPercentage: 0,
    downloadSpeed: '0 KB/s',
    isPaused: false,
    status: 'downloading'
  });
}

const startDrag = (e) => {
  if (isMinimized.value) return;
  
  isDragging.value = true;
  dragStart.x = e.clientX - position.x;
  dragStart.y = e.clientY - position.y;
  document.addEventListener('mousemove', onDrag);
  document.addEventListener('mouseup', stopDrag);
};

const onDrag = (e) => {
  if (!isDragging.value) return;
  position.x = e.clientX - dragStart.x;
  position.y = e.clientY - dragStart.y;
};

const stopDrag = () => {
  isDragging.value = false;
  // 保存位置
  localStorage.setItem('managerPosX', position.x);
  localStorage.setItem('managerPosY', position.y);
  document.removeEventListener('mousemove', onDrag);
  document.removeEventListener('mouseup', stopDrag);
};


const toggleMinimize = () => {
  isMinimized.value = !isMinimized.value;
};
const emit = defineEmits(['close']);
const close = () => {
  emit('close');
};

// 暂停上传
function pauseUpload(file) {
  uploadStore.pauseUpload(file.id);
  eventBus.emit('pause-upload', file.id);
}

// 继续上传
function resumeUpload(file) {
  uploadStore.resumeUpload(file.id);
  eventBus.emit('resume-upload', file.id);
}

// 暂停下载
function pauseDownload(id) {
  downloadStore.pauseDownload(id);
}

// 继续下载
function resumeDownload(id) {
  downloadStore.resumeDownload(id);
}
// 重试上传
function retryUpload(file) {
  if (file.status === 'error' || file.status === 'completed') {
    const retried = uploadStore.retryUpload(file.id);
    eventBus.emit('retry-upload', retried);
  }
}

// 删除上传
function removeUpload(id) {
  uploadStore.removeUpload(id);
}
</script>




<style scoped>
.manager-window {
  position: fixed;
  bottom: 20px;
  right: 20px;
  z-index: 9999;
  transition: all 0.3s ease;
  contain: layout;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  border-radius: 8px;
  overflow: hidden;
  background: white;
}

.window-container {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.header {
  padding: 12px 16px;
  background: #f5f7fa;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  justify-content: space-between;
  align-items: center;
  cursor: move;
  user-select: none;
}

.window-controls {
  display: flex;
  gap: 8px;
}

.window-controls .el-button {
  padding: 4px;
}

.manager-content {
  flex: 1;
  overflow: hidden;
}

.upload-list, .download-list {
  max-height: 400px;
  overflow-y: auto;
  padding: 5px;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 300px;
  color: #909399;
}

.empty-state .el-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.empty-state p {
  margin: 0;
  font-size: 14px;
}
</style>